<template>
  <div class="app-container" v-loading="pageLoading">
    <div class="flex flex-center flex-col-between">
      <div class="text-wrap">
        <div class="desc-text text-primary">
          <i class="el-icon-s-grid" />
          <span class="text">库存盘点</span>
        </div>
      </div>
      <div class="filter-container">
        <el-select class="filter-item" style="width: 200px" v-model="query.queryString.warehouse_id" placeholder="选择仓库"
          clearable>
          <el-option v-for="i in warehouseList" :key="i.key" :label="i.value" :value="i.key"></el-option>
        </el-select>
        <el-select class="filter-item" style="width: 160px" v-model="query.queryString.status" placeholder="选择状态"
          filterable clearable>
          <el-option v-for="(item, index) in statusOptions" :key="index" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
        <el-select class="filter-item" style="width: 160px" v-model="query.queryString.sync_status" placeholder="选择推送状态"
          filterable clearable>
          <el-option v-for="(item, index) in pushOptions" :key="index" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
        <el-input style="width: 300px" placeholder="输入盘点单号按回车" clearable prefix-icon="el-icon-search"
          class="filter-item" @keyup.enter="research" @clear="research" v-model="query.queryString.order_no"></el-input>
        <el-button class="filter-item" type="primary" @click="research">查询</el-button>
        <!--<el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
            </el-button>-->
        <el-button class="filter-item" :icon="Plus" plain type="success" size="small" @click="createItem">新建</el-button>
      </div>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:content="v">
        <span v-if="v.key === 'Status'" class="text-label" :class="statusClass[v.row['Status']]">
          {{ status[v.row['Status']] }}
        </span>
        <span v-else-if="v.key === 'PushStatus'" class="text-label" :class="pushStatusClass[v.row['PushStatus']]">
          {{ pushStatus[v.row['PushStatus']] }}
        </span>
        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation="v">

        <el-button link type="primary" href="#" v-if="v.row['Status'] == 1"
          @click.prevent="updateItem(v.row)">生成差异</el-button>
        <el-button link type="warning" href="#" @click.prevent="goDetail(v.row, v.$index)">查看明细</el-button>
        <el-button link type="danger" href="#" @click.prevent="deleteItem(v.row, v.$index)">删除</el-button>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" v-model:page="query.page" v-model:limit="query.size"
      @change="getList"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" v-model="editFormVisible"></z-form-dialog>
  </div>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
</script>

<script>
import commonMixin from '@/views/_common/mixin'
import store from '@/store'
import _ from 'lodash'
export default {
  mixins: [commonMixin],
  name: 'WmsLikuStocktaking',
  data: function () {
    return {
      api: this.$api.MatStockTaking,
      name: '盘点单',
      columns: [
        { title: '盘点单号', key: 'OrderNo', width: 180 },
        // { title: '类型', key: 'typeName', width: 60 },
        { title: '仓库', key: 'WarehouseNameCode', width: 140 },
        /*{title: '盘点物料', key: 'machine_code', width: 140},*/
        { title: '盘点单说明', key: 'OrderDesc', width: 140 },
        { title: '状态', key: 'Status', width: 90 },
        // { title: '同步状态', key: 'PushStatus', width: 90 },
        { title: '备注', key: 'Remarks' },
        { title: '修改人', key: 'Modifier', width: 100 },
        { title: '最后修改', key: 'ModifyTime', width: 140 },
      ],
      tableProps: {
        border: true,
        opsColWith: 200,
        hideOperations: false,
      },
      pushOptions: [
        { value: '0', label: '待推送' },
        // { value: '1', label: '使用' },
        { value: '1', label: '推送中' },
        { value: '2', label: '推送成功' },
        { value: '3', label: '推送失败' },
      ],
      fields: [
        {
          title: '仓库',
          key: 'warehouse_id',
          name: 'select',
          options: [],
          required: true,
          events: {
            change: this.getzonelist,
          },
          props: { placeholder: '请选择' },
        },
        {
          title: '物料',
          key: 'material_id',

          span: 12,
          name: 'select',
          options: [],
          props: {
            clearable: true,
            filterable: true,
            remote: true,
            remoteMethod: this.getMatOptions,
          },
          events: {
            change: this.chooseMat,
          },
          required: false,
        },
        {
          title: '物料编码',
          key: 'material',
          name: 'textarea',
          props: { rows: 5, placeholder: '输入物料编码需要换行或复制EXCEL中的一列到输入框中' },
        },
        {
          title: '库区',
          key: 'zone_details',
          name: 'select',
          props: { filterable: true, clearable: true, multiple: true },
          options: [],
        },
        {
          title: '库位编码',
          key: 'stock_details',
          name: 'textarea',
          props: { rows: 5, placeholder: '输入库位编码需要换行或复制EXCEL中的一列到输入框中' },
        },
        {
          title: '盘点单说明',
          key: 'order_desc',
          name: 'textarea',
          props: {},
        },
        { title: '备注', key: 'remarks', name: 'textarea' },
      ],
      query: {
        queryString: { warehouse_mode: 1 },
        size: 10,
        page: 1,
      },
      status: { 0: '计划中', 1: '盘点中', 2: '核对中', 9: '已完成' },
      pushStatus: { 0: '待推送', 1: '推送中', 2: '推送成功', 3: '推送失败' },
      statusClass: { 0: 'bg-gray', 1: 'bg-yellow', 2: 'bg-green', 9: 'bg-blue' },
      pushStatusClass: { 0: 'bg-gray', 1: 'bg-yellow', 2: 'bg-green', 3: 'bg-red' },

      warehouseList: [],
      tranData: { data: {}, detail: [] },
      statusOptions: [
        { value: '0', label: '计划中' },
        // { value: '1', label: '使用' },
        { value: '1', label: '盘点中' },
        { value: '2', label: '核对中' },
        { value: '9', label: '已完成' },
      ],
      stockDetail: [],
      initData: { material: '' },
    }
  },
  methods: {
    chooseMat(v) {
      if (v) {
        if (!!!this.data.material) {
          this.data.material = v
        } else {
          this.data.material = this.data.material + '\n' + v
        }
      }
    },
    getMatOptions(query) {
      let data = {
        rows: 100,
        wheres: JSON.stringify([
          {
            name: 'queryCodeName',
            value: query,
          },
        ]),
      }
      this.http
        .post(this.$api.material + 'getPageData', data)
        .then((r) => {
          this.setFieldOptions('material_id', r.rows, 'MaterialCode', ['MaterialCode', 'MaterialName'])
        })
        .catch(() => { })
    },
    materialChange() {
      this.tranData.detail = []
      console.log('🚀 ~ materialChange ~ this.data.material:', this.data.material)

      if (!this.data.material) return
      let data = this.data.material?.split('\n')
      _.forEach(data, (v) => {
        let tmp = _.trim(v)
        if (tmp) {
          this.tranData.detail.push(tmp)
        }
      })
    },
    // 获取库区
    getzonelist(id) {
      let data = {
        rows: 999,
        wheres: JSON.stringify([
          {
            name: 'WarehouseId',
            value: id,
          },
        ]),
      }
      this.http.post(this.$api.zone + 'getPageData', data).then((r) => {
        this.getFieldConfig('zone_details').options = this.arrayOptions(r.rows, 'ZoneId', ['ZoneCode', 'ZoneName'])
      })
      this.getMatOptions()
    },
    goDetail(v) {
      // 立库
      this.$router
        .push({
          name: 'Wms_MatStockTakingDetail',
          query: { MatStockTakingId: v.MatStockTakingId, WarehouseId: v.WarehouseId },
        })
        .catch(() => { })
    },
    deleteItem(v) {
      this.$confirm('确定要删除这条记录？')
        .then(() => {
          this.pageLoading = true
          let url = this.api + 'del'
          let delKeys = [v.MatStockTakingId]
          this.http.post(url, delKeys, this.$ts('正在删除数据') + '....').then((x) => {
            //删除后
            this.getList()
          })
          this.pageLoading = false
        })
        .catch(() => {
        })
    },
    updateItem(v) {
      if (v.Status != '1') {
        this.$message({
          message: '状态为盘点中的才可生成差异',
          type: 'error',
        })
        return false
      }
      this.$confirm('确定要生成差异？', '操作确认')
        .then(() => {
          this.pageLoading = true
          // let url = this.api + 'updateDiff?vId=' + v.MatStockTakingId
          let url = this.api + 'updateDiff'
          this.http
            .get(url, { vId: v.MatStockTakingId }, {})
            .then((r) => {
              this.pageLoading = false
              this.$message({
                message: '操作成功',
                type: 'success',
              })
              this.getList()
            })
            .catch(() => {
              this.pageLoading = false
            })
        })
        .catch(() => {
        })
    },
    stockDetailsChange() {
      this.stockDetail = []
      let data = this.data.stock_details.split('\n')
      _.forEach(data, (v) => {
        let tmp = _.trim(v)
        if (tmp) {
          this.stockDetail.push(tmp)
        }
      })
    },
    submit() {
      let insertUrl = this.apiCreate || this.api + 'stockTakingAdd'
      let updateUrl = this.apiEdit || this.api + 'update'
      let url = this.data.id ? updateUrl : insertUrl
      let check = this.validataData(this.fields, this.data)
      if (!check) return
      let data = this.formatBeforeSave(this.data)
      if (!this.data.stock_details) {
        data['stock_details'] = []
      } else {
        this.stockDetailsChange()
        data['stock_details'] = this.stockDetail
      }
      if (!this.data.zone_details) {
        data['zone_details'] = []
      } else {
        data['zone_details'] = this.data.zone_details
      }
      delete data.data.zone_details
      delete data.data.stock_details
      this.submitLoading = true
      this.http
        .post(url, data)
        .then((r) => {
          this.editFormVisible = false
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    formatBeforeSave(data) {
      let datatmp = _.cloneDeep(data)
      delete datatmp['material']
      this.materialChange()
      this.tranData.data = datatmp
      return this.tranData
    },
    formatList(list) {
      //依据实际需求处理
      let tmp = _.cloneDeep(list)
      /*let tmpObj = _.keyBy(this.statusOptions, 'value')*/
      return tmp.map((i) => {
        i.warehouse_name_code = i.warehouse_code + ' ' + i.warehouse_name
        return i
      })
      return tmp
    },
    formatQuery(query) {
      return {
        ...query,
        queryString: JSON.stringify(query.queryString),
      }
    },
    getList() {
      this.pageLoading = true
      let url = this.api + 'getList'
      this.http
        .get(url, this.formatQuery(this.query))
        .then((r) => {
          this.list = this.formatList(r.rows)
          this.total = r.Total
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
  },
  created: function () {
    let data = {
      rowsL: 999,
      wheres: JSON.stringify([]),
    }
    this.http
      .post(this.$api.warehouse + 'getPageData', data)
      .then((r) => {
        this.warehouseList = this.arrayOptions(r.rows, 'WarehouseId', ['WarehouseCode', 'WarehouseName'])
        this.setFieldOptions('warehouse_id', r.rows, 'WarehouseId', ['WarehouseCode', 'WarehouseName'])
      })
      .catch(() => { })

    this.getList()
  },
}
</script>
<style scoped lang="scss">
.text-wrap {
  height: 40px;
  position: relative;
  padding-bottom: 8px;
  display: flex;

  .desc-text {
    //  display: inline-block;
    margin-top: 7px;
    font-weight: bold;
    //margin-bottom: 3px;
    font-size: 14px;
    white-space: nowrap;
    border-bottom: 2px solid #7300e6;

    i {
      font-size: 16px;
      position: relative;
      top: 1px;
      margin-right: 2px;
    }
  }
}
</style>
